package com.hlkj.baojin.service.impl;

import com.google.common.collect.Maps;
import com.hlkj.baojin.constant.BaojinConstant;
import com.hlkj.baojin.constant.enums.RoleEnum;
import com.hlkj.baojin.constant.enums.SmsTypeEnum;
import com.hlkj.baojin.dao.ICompanyDao;
import com.hlkj.baojin.dao.IUserDao;
import com.hlkj.baojin.dao.repository.AlarmRecordRepository;
import com.hlkj.baojin.dao.repository.CompanyRepository;
import com.hlkj.baojin.dao.repository.DeviceRepository;
import com.hlkj.baojin.dao.repository.EarlyAlarmRecordRepository;
import com.hlkj.baojin.entity.Company;
import com.hlkj.baojin.entity.CompanyArea;
import com.hlkj.baojin.entity.User;
import com.hlkj.baojin.entity.dto.CompanyDto;
import com.hlkj.baojin.entity.dto.CompanySearchDto;
import com.hlkj.baojin.entity.dto.ModelList;
import com.hlkj.baojin.entity.vo.CameraInfo;
import com.hlkj.baojin.jwt.JwtUser;
import com.hlkj.baojin.service.*;
import com.hlkj.baojin.utils.EncryptUtil;
import com.hlkj.baojin.utils.ErrororUtil;
import com.hlkj.baojin.utils.bean.JsonResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author HULIN
 * @created with: baojin
 * @package com.hlkj.baojin.service.impl
 * @description:
 * @date 2018/12/17 12:55
 * @modified By:
 * @Copyright © 2018 HAILIANG Info. Tech Ltd. All rights reserved.
 */
@Service
public class CompanyServiceImpl implements CompanyService {

    @Autowired
    private ICompanyDao companyDao;
    @Autowired
    private IUserDao userDao;
    @Autowired
    private CompanyRepository companyRepository;
    @Autowired
    private IUserService userService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private DeviceRepository deviceRepository;
    @Autowired
    private AlarmRecordRepository alarmRecordRepository;
    @Autowired
    private EarlyAlarmRecordRepository earlyAlarmRecordRepository;
    @Autowired
    private HKWebService hkWebService;
    @Autowired
    private ICompanyAreaService companyAreaService;

    @Override
    @Transactional
    public void saveCompany(CompanyDto companyDto) {
        JwtUser currentUser = userService.getCurrentUser();
        Company companyByName = companyDao.findByNameAndDelete(companyDto.getName(), BaojinConstant.IS_NO_DELETE);
        ErrororUtil.isFalseNull(companyByName, "新增公司", "该公司名称已注册");

        Company companyDB = companyDao.findByCompanyPrincipalPhoneAndDelete(companyDto.getCompanyPrincipalPhone(), BaojinConstant.IS_NO_DELETE);
        ErrororUtil.isFalseNull(companyDB, "新增公司", "公司负责人手机号已被注册");
        User userDB = userDao.findByUsername(companyDto.getCompanyPrincipalPhone());
        ErrororUtil.isFalseNull(userDB, "新增公司", "公司负责人手机号已被注册");
        if (StringUtils.isNotBlank(companyDto.getIndexNum())) {
            ErrororUtil.isFalseNull(companyDao.findByIndexNumAndDelete(companyDto.getIndexNum(), BaojinConstant.IS_NO_DELETE),
                    "新增公司", "索引编号已使用,请更换");
        }

        Company company = new Company(currentUser.getId(), System.currentTimeMillis(), BaojinConstant.IS_NO_DELETE);
        BeanUtils.copyProperties(companyDto, company);
        try {
            companyDao.save(company);
            String password = "123456";
            User user = new User(company.getCompanyPrincipalPhone(), new BCryptPasswordEncoder().encode(password),
                    company.getId(), 1, Collections.singletonList(RoleEnum.ROLE_DEPTADMIN.toString()));
            smsService.sendSms(company.getCompanyPrincipalPhone(), SmsTypeEnum.USER_SET_UP, password);
            userDao.save(user);
        } catch (Exception e) {
            ErrororUtil.isError("新增公司", "保存失败");
        }
    }

    @Override
    @Transactional
    public void updateCompany(CompanyDto companyDto) {
        JwtUser currentUser = userService.getCurrentUser();
        ErrororUtil.isTrue(StringUtils.isBlank(companyDto.getId()),
                "更新公司", "数据异常");
        ErrororUtil.isTrue(StringUtils.isNotBlank(companyDto.getCompanyPrincipalPhone()),
                "更新公司", "无法更新公司负责人手机号");

        if (StringUtils.isNotBlank(companyDto.getIndexNum())) {
            Company companyTemp = companyDao.findByIndexNumAndDelete(companyDto.getIndexNum(), BaojinConstant.IS_NO_DELETE);
            if (companyTemp != null && !companyTemp.getId().equals(companyDto.getId())) {
                ErrororUtil.isError("更新公司", "索引编号已使用,请更换");
            }
        }

        Company company = new Company();
        BeanUtils.copyProperties(companyDto, company);
        company.setUpdateMan(currentUser.getId());
        company.setUpdateTime(System.currentTimeMillis());
        companyRepository.updateCompanyNotNull(company);
    }

    @Override
    @Transactional
    public void deleteCompany(String companyId) {
        //ErrororUtil.isError("删除公司", "存在异常的设备, 无法删除");

        Company company = companyDao.findByIdAndDelete(companyId, BaojinConstant.IS_NO_DELETE);
        ErrororUtil.isTrueNull(company, "删除公司", "不存在所删除公司");

        JwtUser currentUser = userService.getCurrentUser();
        Company companyDetele = new Company(companyId, currentUser.getId(), System.currentTimeMillis(), BaojinConstant.IS_DELETE);

        User companyUser = userService.getUserDao().findByDeptId(companyId);
        companyUser.setUsername(EncryptUtil.encrypt(companyUser.getUsername() + System.currentTimeMillis()));

        try {
            companyRepository.updateCompanyNotNull(companyDetele);
            userDao.save(companyUser);
            List<CompanyArea> companyAreaList = companyAreaService.getCompanyAreaDao().
                    findByBelongCompanyAndDelete(companyId, BaojinConstant.IS_NO_DELETE);
            companyAreaList.stream().forEach(companyArea -> companyAreaService.deleteCompanyArea(companyArea.getId()));
        } catch (Exception e) {
            ErrororUtil.isError("删除公司", "删除失败");
        }
    }

    @Override
    public JsonResult findCompany(CompanySearchDto companySearchDto) {
        ModelList<Company> companyModelList = companyRepository.getCompany(companySearchDto);
        List<Company> companyList = companyModelList.getList();

        List<CompanyDto> companyDtoList = new ArrayList<>();
        for (Company company : companyList) {
            CompanyDto companyDto = new CompanyDto();
            BeanUtils.copyProperties(company, companyDto);
            companyDtoList.add(companyDto);
        }

        Map maps = Maps.newHashMap();
        maps.put("list", companyDtoList);
        maps.put("count", companyModelList.getCount());

        return JsonResult.success(maps);
    }

    @Override
    public CompanyDto findCompanyById(String companyId) {

        Company company = companyDao.findByIdAndDelete(companyId, BaojinConstant.IS_NO_DELETE);
        CompanyDto companyDto = new CompanyDto();
        BeanUtils.copyProperties(company, companyDto);
        return companyDto;
    }

    @Override
    public String getCompanyNameById(String companyId) {
        Company company = companyDao.findByIdAndDeleteIn(companyId, new Integer[]{0, 1});
        if (companyDao.findByIdAndDeleteIn(companyId, new Integer[]{0, 1}) == null) {
            ErrororUtil.isError("公司查询", "数据异常");
        }
        return company.getName();
    }

    @Override
    public List<String> getIdsByNameLike(String name) {
        return companyRepository.getIdsByNameLike(name);
    }

    @Override
    public List<CompanyDto> getCompanyList() {
        List<Company> companyList = companyDao.findByDeleteNot(BaojinConstant.IS_DELETE);

        List<CompanyDto> companyDtoList = new ArrayList<>();
        for (Company company : companyList) {
            CompanyDto companyDto = new CompanyDto();
            companyDto.setId(company.getId());
            companyDto.setName(company.getName());
            companyDto.setMonitorTreeNum(company.getMonitorTreeNum());
            companyDtoList.add(companyDto);
        }
        return companyDtoList;
    }

    @Override
    public List cameraList(String companyId) {
        Company company = companyDao.findByIdAndDelete(companyId, BaojinConstant.IS_NO_DELETE);
        return hkWebService.getOrgAndCameraZTreeByOrgIndexCode(company.getMonitorTreeNum());
    }

}
